package com.zc.config;

import com.zc.pojo.LoginUser;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @description:
 * @author: cong
 * @create: 2024/8/1
 */
@Configuration
public class RedisConfig {
    @Bean
    public <T> RedisTemplate<String, T> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, T> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        FastJsonRedisSerializer<LoginUser> redisSerializer = new FastJsonRedisSerializer<>(LoginUser.class);

        // key采用String的序列化方式
        redisTemplate.setKeySerializer(new StringRedisSerializer());

        // value序列化方式采用fastJsonRedisSerializer
        redisTemplate.setValueSerializer(redisSerializer);

        // hash的key也采用String的序列化方式
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        // hash的value序列化方式采用fastJsonRedisSerializer
        redisTemplate.setHashValueSerializer(redisSerializer);

        // 用于确保RedisTemplate在应用程序启动时被正确配置和初始化
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}
